<template>
  <div class="text-edit" ref="editor"></div>
</template>

<script lang="ts">
import Vue from 'vue'
import E from 'wangeditor'
import { uploadCourseImg } from '@/services/course'
export default Vue.extend({
  name: 'TextEditor',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  // 组件已经渲染好，可以操作 DOM
  mounted () {
    this.initEditor()
  },
  methods: {
    initEditor () {
      const editor = new E(this.$refs.editor as any)
      // 事件监听需要在初始化之前
      editor.config.onchange = (value: string) => {
        this.$emit('input', value)
      }
      editor.create()
      console.log(this.value)
      // 设置初始值，需要在初始化以后
      editor.txt.html(this.value)

      editor.config.customUploadImg = async function (resultFiles: any, insertImgFn: any) {
        // 把用户选择的 resiltFiles 上传到服务器
        const fd = new FormData()
        fd.append('file', resultFiles[0])
        const { data } = await uploadCourseImg(fd)
        insertImgFn(data.data.name)
      }
    }
  }
})
</script>

<style lang="scss" scope></style>
